import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { Logger } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { HttpExceptionFilter } from './core/filter/http-exception/http-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 注册全局过滤器 拦截错误
  app.useGlobalFilters(new HttpExceptionFilter());

  // 获取配置服务
  const configService = app.get(ConfigService);

  // 根据环境变量设置全局路由前缀
  const prefix = configService.get<string>('GLOBAL_PREFIX');
  app.setGlobalPrefix(prefix);

  // swagger接口文档配置
  const config = new DocumentBuilder()
    .setTitle('swagger接口文档')
    .setDescription('NestJS项目接口文档')
    .setVersion('1.0')
    .addBearerAuth()
    .build();
  const swaggerUrlPrefix = configService.get<string>('SWAGGER_URL_SUFFIX');
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup(swaggerUrlPrefix, app, document);

  // 根据环境变量设置端口
  const port = configService.get<number>('PORT') || 3088;
  await app.listen(port);

  const projectName = configService.get<string>('PROJECT_NAME');
  const host = configService.get<string>('HOST');

  Logger.log(
    `[${projectName}] 项目启动成功！接口文档: ${host}:${port}/${swaggerUrlPrefix}`
  );
}

bootstrap();
